<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" >
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button>批量操作<a-icon type="down" /></a-button>
      </a-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon" />
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px"  @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a @click="refresh"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <col-setting v-if="defColumns.length>0" :defColumns="defColumns" v-model="settingColumns" />
        </span>
      </div>
      <a-table
        size="middle"
        bordered
        rowKey="formDataId"
        :columns="getColumns"
        :data-source="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:getCheckboxProps}"
        @change="handleTableChange"
        :customRow="customRow"
      >
        <template slot="switch" slot-scope="text">
          <a-switch :checked="text" :disabled="true" />
        </template>
        <template slot="uploadImg" slot-scope="text, record, index">
          <div v-if="Array.isArray(text) && text.length > 0" class="j-table-slot-view">
            <img v-for="(item,imgIndex) of text" class="upload-img" :src="item.url" alt=" " :key="imgIndex" :preview="index" v-show="imgIndex===0"/>
          </div>
        </template>
        <template slot="uploadFile" slot-scope="text">
          <div v-if="Array.isArray(text) && text.length > 0" class="j-table-slot-view">
            <a-button type="primary" icon="download" size="small" ghost @click="downloadRowFile(text)">下载</a-button>
          </div>
        </template>
        <template slot="user" slot-scope="text">
          <span>{{getRealname(text)}}</span>
        </template>
        <template slot="dept" slot-scope="text">
          <span>{{initDepartComponent(text)}}</span>
        </template>
        <template slot="status" slot-scope="text,record, index">
          <span class="status" :class="{yellow:record.status === 1,green:record.status === 2}">{{filterDictTextByCache('bpmn_status', text)}}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a v-if="record.status === 0 || record.status === 3 || record.status === 5" @click="startInstance(record)">提交</a>
          <a-divider v-if="record.status === 0 || record.status === 3 || record.status === 5" type="vertical" />
          <a v-if="record.status === 0 || record.status === 3 || record.status === 5" @click="handleEdit(record,false)">编辑</a>
          <a  v-if="record.status !== 0 && record.status !== 3 && record.status !== 5" @click="handleEdit(record,true)">详情</a>
          <a-divider v-if="record.status === 0 || record.status === 3 || record.status === 5" type="vertical" />
          <a-popconfirm
            v-if="record.status === 0 || record.status === 3 || record.status === 5"
            title="确定删除吗?"
            @confirm="() => handleDelete(record.formDataId)"
          >
            <a >删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <!-- 表单弹窗区域 -->
    <j-modal
      width="80%"
      :title="kfbTitle"
      :visible.sync="desformApplyVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      :destroyOnClose="true"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button key="back" @click="desformApplyHandleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" @click="desformApplyHandleOk">
          确定
        </a-button>
      </template>
      <a-spin size="large" :spinning="spinning">
        <k-form-build ref="kfb" :value="formData" :disabled="disabledAll" />
      </a-spin>
    </j-modal>
    <task-modal ref="taskModal" title="历史" :taskData="taskData" type="history"></task-modal>
  </a-card>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { saveOrUpdate, startInstance } from '@/api/process'
import { ProcessMixins } from './mixins/ProcessMixins'
import { getAction } from '@/api/manage'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { getCheckboxProps } from '@/utils/bpmn'
export default {
  name: 'ProcessList',
  mixins: [JeecgListMixin, ProcessMixins],
  data() {
    return {
      fullscreen: false,
      switchFullscreen: true,
      kfbTitle: '新增',
      desformApplyVisible: false,
      disabledAll: false, // 表单禁用控制
      url: {
        list: '/activiti/formData/list',
        deleteBatch: '/activiti/formData/deleteBatch',
        delete: '/activiti/formData/delete',
        getKfdJson: '/activiti/form/getFormByProcessDefinitionId',
        getNewKfdJson: '/activiti/form/getFormDeploymentByModelId' // 获取组件自定义表单
      },
      rootUrLReplace: '/ProcessList/', // 根据这个截取url参数
      spinning: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    filterDictTextByCache: filterDictTextByCache,
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      params.createBy = this.userInfo().username// 添加用户查询的条件
      // params.type = 1
      params.modelId = this.id
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          res.result.records.forEach((item) => {
            item.formData = JSON.parse(item.formData)
            this.setUserName(item.formData)
          })
          this.getUserList()
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getCheckboxProps(record) {
      return getCheckboxProps(record)
      // return {
      //   props: {
      //     disabled: !(record.status === 0 || record.status === 3) // Column configuration not to be checked
      //   }
      // }
    },
    handleEdit(record, disabled) { // 编辑流程
      this.disabledAll = disabled
      this.taskData = record
      this.kfbTitle = '编辑'
      this.getKfdJson(record)
      this.desformApplyVisible = true
    },
    async getKfdJson(item) { // 不同版本流程获取不同版本
      try {
        this.spinning = true
        const res = await getAction(this.url.getKfdJson, { modelId: item.modelId, processDefinitionId: item.processDefinitionId })
        if (res.success) {
          if (!res.result) {
            return this.$message.warning('该工单的未设计表单')
          }
          this.formData = JSON.parse(res.result.htmlJson)
          this.$nextTick(() => {
            this.$refs.kfb.setData(item.formData)
          })
          this.spinning = false
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    handleAdd() { // 新增流程
      if (!this.modelData.processDefinitionId) {
        this.$message.warning('请发布流程再新增')
        return false
      }
      this.disabledAll = false
      this.kfbTitle = '新增'
      this.taskData = {}
      this.formData = this.newFormData
      this.desformApplyVisible = true
    },
    async desformApplyHandleOk() { // 流程表单保存
      try {
        const formData = await this.$refs.kfb.getData()
        if (!this.modelData.processDefinitionId) {
          this.$message.warning('请先发布流程')
          return false
        }
        const res = await saveOrUpdate({
          modelId: this.modelData.modelId,
          formId: this.modelData.id,
          processDefinitionId: this.modelData.processDefinitionId,
          formData: JSON.stringify(formData),
          id: this.taskData.formDataId,
          type: 1
        })
        if (res.success) {
          this.desformApplyVisible = false
          this.$message.success('保存成功')
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    desformApplyHandleCancel() { // 流程弹窗取消
      this.desformApplyVisible = false
    },
    startInstance(item) { // 提交流程
      startInstance({
        modelId: item.modelId,
        formDataId: item.formDataId,
        processDefinitionId: item.processDefinitionId
      }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleHistory(data) { // 点击查看进度
      this.taskData = data
      this.$refs.taskModal.editModalVisible = true
    },
    customRow(record, index) {
      return {
        on: {
          dblclick: () => {
            if (record.status !== 0) {
              this.taskData = record
              this.$refs.taskModal.editModalVisible = true
            } else {
              this.$message.warning('该单据未提交')
            }
          }
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
  .j-table-slot-view {
    font-size: 12px;
    font-style: italic;
    .upload-img {
      max-width: 80px;
      max-height: 18px;
    }
  }
  .status{
    padding: 3px 5px;
    border-radius: 5px;
  }
  .yellow{
    background-color: yellow;
    color:#6d5c5c
  }
  .green {
    background-color: #38e038;
    color:#fff
  }
</style>
